package com.ironone.streaming;

import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.facebook.widget.LoginButton;
import com.ironone.streaming.application.CusAlrtBtnTypes;
import com.ironone.streaming.application.CusAlrtIconTypes;
import com.ironone.streaming.application.CustomAlertDialog;
import com.ironone.streaming.application.FormObject;
import com.ironone.streaming.application.MainApplication;
import com.ironone.streaming.application.MySlidingPaneLayout;
import com.ironone.streaming.comm.HTTPManager;
import com.ironone.streaming.exception.ExceptionHandler;
import com.ironone.streaming.lite.R;
import com.ironone.streaming.mediaplayer.MediaPlayerStatus;
import com.ironone.streaming.mediaplayer.MyMediaPlayer;
import com.ironone.streaming.mediaplayer.MyMediaPlayerActivityNotifyStatus;
import com.ironone.streaming.mediaplayer.MyMediaPlayerService;
import com.ironone.streaming.mediaplayer.MyMediaPlayerServiceNotifyStatus;
import com.ironone.streaming.model.EventsDataModel;
import com.ironone.streaming.model.ModelMapper;
import com.ironone.streaming.model.NowPlayingDataModel;
import com.ironone.streaming.model.OurShowsDataModel;
import com.ironone.streaming.model.ResponseDataModel;

public class RadioPlayerActivity extends FragmentActivity {
	Animation rotation;
	Animation rotation_;
	TextView nowPlayingInfo1, nowPlayingInfo2, nowPlayingInfo_screenname;
	ImageView albumart_image, playbtn_loadingcircle;
	ImageView powered_by_blue_icon, powered_by_gray_icon;
	/** Jeya */
	String username;
	LinearLayout nowPlayingWhiteLine;
	/** Jeya */

	int timerToStopPlayback = 5000; // In milliseconds. After this time paused
									// player will be reseted.

	BroadcastReceiver br_commonReceiver;
	private Handler handler;
	Runnable runnable;
	boolean stopAnimation = true;
	AnimationSet animation;
	AnimationSet animationp; /* For PowerdBy */;
	Animation playerLineAnimation1;
	ImageView playerLine1;
	// The main content view based on code from:
	// http://blog.bignerdranch.com/2765-exploring-slidingpanelayout
	MySlidingPaneLayout mPane;
	ToggleButton playButton, hdButton;
	LinearLayout linear_topcontainer, linear_bottomcontainer,
			linear_orangelinecontainer, linear_nowplayingcontainer,
			bottom_view_bottom, bottom_view_top_wrapper,
			linear_nowplayingcontainer_, linear_albumartcontainer;

	// AlbumArt Fragment UI components
	TextView errorTextView;
	LinearLayout loading_wrapper;
	Button btnMenu;
	ImageView retryButton_circle, albumart_bg;
	ImageButton retryButton_flame;

	// Menu Fragment UI components
	ImageView roundfb_profilepic, roundfb_profilepic_circle;
	LinearLayout topPanel_left, topPanel_right_inner_down;
	LoginButton fbLoginButton;
	TextView textView_firstname, textView_welcome;
	Button homebtn;

	int profilePicWidth = 400;
	static boolean isFirstTime = true;

	int playBtnClickCheck = 5000;
	int nowPlayingSyncTimer = 5000;
	NowPlayingDataModel npdm_one;

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
			// overridePendingTransition(R.anim.slide_right_to_middle,
			// R.anim.slide_middle_to_left);
			// overridePendingTransition(R.animator.activity_translate_anim1,R.animator.activity_translate_anim2);
			setContentView(R.layout.final_radio_player);
			username = "";
			mPane = (MySlidingPaneLayout) findViewById(R.id.pane);
			mPane.setSliderFadeColor(100 * 0x1000000);
			mPane.setParallaxDistance(100); // MainApplication.getScreenWidth(this,
											// true)
			mPane.setShadowResource(R.drawable.slidingpane_line);

			getSupportFragmentManager().beginTransaction()
					.add(R.id.pane1, new MainMenuFragment(), "pane1").commit();
			getSupportFragmentManager().beginTransaction()
					.add(R.id.pane2, new AlbumArtFragment(), "pane2").commit();

			/*
			 * mPane.setPanelSlideListener(new PanelSlideListener() {
			 * 
			 * @Override public void onPanelSlide(View arg0, float arg1) { }
			 * 
			 * @Override public void onPanelOpened(View arg0) { }
			 * 
			 * @Override public void onPanelClosed(View arg0) { } });
			 */

			playButton = (ToggleButton) findViewById(R.id.toggleplaybutton);
			hdButton = (ToggleButton) findViewById(R.id.togglehdbutton);
			playbtn_loadingcircle = (ImageView) findViewById(R.id.playbtn_loadingcircle);
			/** Jeya */
			nowPlayingWhiteLine = (LinearLayout)findViewById(R.id.nowPlayingWhiteLine);
			//nowPlayingInfo_two_copy = (TextView) findViewById(R.id.nowPlayingInfo_two_copy);
			/** Jeya */

			linear_nowplayingcontainer_ = (LinearLayout) findViewById(R.id.linear_nowplayingcontainer_);
			linear_bottomcontainer = (LinearLayout) findViewById(R.id.linear_bottomcontainer);
			playerLine1 = (ImageView)findViewById(R.id.playerline);
            powered_by_gray_icon = (ImageView) findViewById(R.id.powered_by_gray_icon);
            powered_by_blue_icon = (ImageView) findViewById(R.id.powered_by_blue_icon);
            powered_by_gray_icon.setAlpha(48);

			albumart_image = (ImageView) findViewById(R.id.albumart_image);
			nowPlayingInfo1 = (TextView) findViewById(R.id.nowPlayingInfo_one);
			nowPlayingInfo2 = (TextView) findViewById(R.id.nowPlayingInfo_two);
			nowPlayingInfo_screenname = (TextView) findViewById(R.id.nowPlayingInfo_screenname);
			nowPlayingInfo1.setTextSize(FormObject.getInstance().getTextSize());
			nowPlayingInfo2.setTextSize(FormObject.getInstance().getTextSize());
			//nowPlayingInfo_two_copy.setTextSize(FormObject.getInstance().getTextSize());
			nowPlayingInfo_screenname.setTextSize(FormObject.getInstance()
					.getTextSize() + 5);

		
			handler = new Handler();
			int animValp = MainApplication.ANIME_DURATION_POWBY;
			Animation fadeInp = new AlphaAnimation(0, 1);
			fadeInp.setInterpolator(new AccelerateInterpolator()); // add this
			fadeInp.setDuration(animValp);

			Animation fadeOutp = new AlphaAnimation(1, 0);
			fadeOutp.setInterpolator(new DecelerateInterpolator()); // and this
			fadeOutp.setStartOffset(animValp);
			fadeOutp.setDuration(animValp);
			
			animationp = new AnimationSet(false); // change to false
            animationp.addAnimation(fadeInp);
            animationp.addAnimation(fadeOutp);
            animationp.setRepeatCount(0);
            powered_by_blue_icon.setAnimation(animationp);

            animationp.setAnimationListener(new AnimationListener() {
                    public void onAnimationEnd(Animation animation) {
                            powered_by_blue_icon.setAlpha(0);
                            powered_by_gray_icon.setEnabled(true);
                            //}
                    }
                    public void onAnimationRepeat(Animation animation) {
                    }
                    public void onAnimationStart(Animation animation) {
                            powered_by_blue_icon.setAlpha(192);
                            powered_by_gray_icon.setEnabled(false);
                    }
            });

            powered_by_gray_icon.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                            animatePoweredByIcon();
                    }
            });
			
			/** Jeya */
			rotation = AnimationUtils.loadAnimation(getApplicationContext(),
					R.anim.blink);
			rotation.setAnimationListener(new AnimationListener() {

				@Override
				public void onAnimationStart(Animation animation) {
					playbtn_loadingcircle.setVisibility(View.VISIBLE);
				}

				@Override
				public void onAnimationEnd(Animation animation) {
					//playbtn_loadingcircle.setVisibility(View.VISIBLE);
				}

				@Override
				public void onAnimationRepeat(Animation animation) {
				}
			});
			/** Jeya */

			rotation_ = AnimationUtils.loadAnimation(getApplicationContext(),
					R.anim.rotate_button);
			rotation_.setRepeatCount(Animation.INFINITE);

			Intent serviceIntent = new Intent(getApplicationContext(),
					MyMediaPlayerService.class);
			startService(serviceIntent);

			int animVal = MainApplication.ANIME_DURATION;
			Animation fadeIn = new AlphaAnimation(0, 1);
			fadeIn.setInterpolator(new DecelerateInterpolator()); // add this
			fadeIn.setDuration(animVal);

			Animation fadeOut = new AlphaAnimation(1, 0);
			fadeOut.setInterpolator(new AccelerateInterpolator()); // and this
			fadeOut.setStartOffset(animVal);
			fadeOut.setDuration(animVal);

			animation = new AnimationSet(false); // change to false
			animation.addAnimation(fadeOut);
			animation.addAnimation(fadeIn);
			animation.setRepeatMode(Animation.REVERSE);
			animation.setRepeatCount(Animation.INFINITE);
			hdButton.setChecked(true); // Default go with HD stream
			hdButton.setAnimation(animation);

			animation.setAnimationListener(new AnimationListener() {
				public void onAnimationEnd(Animation animation) {
					if (stopAnimation) {
						animation.reset();
						animation.startNow();
					}
				}

				public void onAnimationRepeat(Animation animation) {
				}

				public void onAnimationStart(Animation animation) {
				}
			});
			
			playerLineAnimation1 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.player_line_right_to_left_1);

			hdButton.clearAnimation();
			nowPlayingPolling();
		} catch (Exception e) {
			isFirstTime = false;
			CustomAlertDialog alertDialog = new CustomAlertDialog(this,
					CusAlrtBtnTypes.OK, CusAlrtIconTypes.DUCK);
			alertDialog.setTitleText(getString(R.string.what_the_duck_));
			//alertDialog.setMessageText(getString(R.string.something_snapped));
			alertDialog.show();
		}
	}

	private void animatePoweredByIcon() {
                powered_by_blue_icon.startAnimation(animationp);
    }

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		try {
			super.onWindowFocusChanged(hasFocus);

			if (!hasFocus)
				return;

			int bot_height = (linear_bottomcontainer.getHeight());
			int playBtnSize = (int) (bot_height * 1.5);
			RelativeLayout.LayoutParams pParam = (RelativeLayout.LayoutParams) playButton
					.getLayoutParams();
			pParam.height = playBtnSize;
			pParam.width = playBtnSize;
			playButton.setLayoutParams(pParam);

			RelativeLayout.LayoutParams plParam = (RelativeLayout.LayoutParams) playbtn_loadingcircle
					.getLayoutParams();
			plParam.height = playBtnSize;
			plParam.width = playBtnSize;
			playbtn_loadingcircle.setLayoutParams(plParam);

			//linear_nowplayingcontainer_.getBackground().setAlpha(96); // setAlpha(192);

			profilePicWidth = topPanel_left.getWidth();
			profilePicWidth = (int) (profilePicWidth * 0.6);

			RelativeLayout.LayoutParams hxParams = (RelativeLayout.LayoutParams) roundfb_profilepic
					.getLayoutParams();
			hxParams.height = (int) (profilePicWidth - (profilePicWidth * 0.05)); // -16;
			hxParams.width = (int) (profilePicWidth - (profilePicWidth * 0.05)); // -16;
			roundfb_profilepic.setLayoutParams(hxParams);

			RelativeLayout.LayoutParams hwParams = (RelativeLayout.LayoutParams) roundfb_profilepic_circle
					.getLayoutParams();
			hwParams.height = profilePicWidth;
			hwParams.width = profilePicWidth;
			roundfb_profilepic_circle.setLayoutParams(hwParams);

			int fbLoginBtnWidth = (int) (topPanel_right_inner_down.getWidth() * 0.4);
			LinearLayout.LayoutParams hqParams = (LayoutParams) fbLoginButton
					.getLayoutParams();
			hqParams.width = fbLoginBtnWidth;
			hqParams.height = (int) (fbLoginBtnWidth / 3);
			fbLoginButton.setLayoutParams(hqParams);

			LinearLayout.LayoutParams hpParams = (LayoutParams) homebtn
					.getLayoutParams();
			hpParams.width = fbLoginBtnWidth;
			hpParams.height = (int) (fbLoginBtnWidth / 3);
			homebtn.setLayoutParams(hpParams);

			int size = (int) (FormObject.getInstance().getTextSize() * 0.5);
			if (errorTextView != null)
				errorTextView.setTextSize(size);

			if (FormObject.getInstance().getFbLoginStatus()) {
				fbLoginButton
						.setBackgroundResource(R.drawable.menufblogoutbutton); // Logout
																				// image
				if (FormObject.getInstance().getFbName() != null
						&& !FormObject.getInstance().getFbName().equals("")) {
					textView_firstname.setText(FormObject.getInstance()
							.getFbName().split(" ")[0]);
					/** Jeya */
					username = " ";//FormObject.getInstance().getFbName().split(" ")[0];
					/** Jeya */
				}

				// Used to avoid blank circle with no image display
				if (FormObject.getInstance().getFbProfilePicture() == null) {
					Bitmap drfault_bm = BitmapFactory.decodeResource(
							getResources(), R.drawable.default_profile_pic);
					roundfb_profilepic.setImageBitmap(MainApplication
							.getRoundedRectBitmap(this, drfault_bm, true));
				} else {
					Bitmap convImg = MainApplication
							.getByteArrToBitmap(FormObject.getInstance()
									.getFbProfilePicture());
					Bitmap img1 = MainApplication.getRoundedRectBitmap(this,
							convImg, true);
					roundfb_profilepic.setImageBitmap(img1);
				}
			} else {
				fbLoginButton
						.setBackgroundResource(R.drawable.menufbloginbutton); // Login
																				// image
				textView_firstname.setText(R.string.stranger);

				// Used to avoid blank circle with no image display
				Bitmap drfault_bm = BitmapFactory.decodeResource(
						getResources(), R.drawable.default_profile_pic);
				roundfb_profilepic.setImageBitmap(MainApplication
						.getRoundedRectBitmap(this, drfault_bm, true));
			}

			textView_welcome
					.setTextSize(FormObject.getInstance().getTextSize());
			textView_firstname.setTextSize(FormObject.getInstance()
					.getTextSize());
		} catch (Exception e) {
			CustomAlertDialog alertDialog = new CustomAlertDialog(this,
					CusAlrtBtnTypes.OK, CusAlrtIconTypes.DUCK);
			alertDialog.setTitleText(getString(R.string.what_the_duck_));
			//alertDialog.setMessageText(getString(R.string.something_snapped));
			alertDialog.show();
		}
	}

	/**
	 * private void animatePoweredByIcon() {
	 * powered_by_blue_icon.startAnimation(animationp); }
	 */

	@Override
	protected void onPause() {
		try {
			super.onPause();
			MyMediaPlayer.setIsPlayerOnBackground(true);
			startNotificationOnStatusBar();
			unregisterReceiver(br_commonReceiver);
		} catch (Exception e) {
			/*
			 * CustomAlertDialog alertDialog = new CustomAlertDialog(this,
			 * CusAlrtBtnTypes.OK, CusAlrtIconTypes.DUCK);
			 * alertDialog.setTitleText(getString(R.string.what_the_duck_));
			 * alertDialog
			 * .setMessageText(getString(R.string.something_snapped));
			 * alertDialog.show();
			 */
		}
	}

	@Override
	protected void onResume() {
		try {
			super.onResume();
			//playbtn_loadingcircle = (ImageView) findViewById(R.id.playbtn_loadingcircle);
			MyMediaPlayer.setIsPlayerOnBackground(false);
			//animatePoweredByIcon(); // Just a fancy feature

			myMediaPlayerServiceCallbacks();
			if(MyMediaPlayer.isPlaying())
			{
				playbtn_loadingcircle.setVisibility(View.VISIBLE);
			}
			stopNotificationOnStatusBar();

			// AlbumArt Fragment
			View viewAlbumArt = getSupportFragmentManager().findFragmentByTag(
					"pane2").getView();
			loading_wrapper = (LinearLayout) viewAlbumArt
					.findViewById(R.id.loading_wrapper);
			errorTextView = (TextView) viewAlbumArt
					.findViewById(R.id.errorTextView);
			btnMenu = (Button) viewAlbumArt.findViewById(R.id.btnMenu);
			albumart_bg = (ImageView) viewAlbumArt
					.findViewById(R.id.albumart_bg);
			retryButton_flame = (ImageButton) viewAlbumArt
					.findViewById(R.id.retryButton_flame);
			retryButton_circle = (ImageButton) viewAlbumArt
					.findViewById(R.id.retryButton_circle);
			if (retryButton_flame != null)
				retryButton_flame.setEnabled(false);
			if (retryButton_circle != null)
				retryButton_circle.setEnabled(false);

			// Main menu Fragment
			// View viewMainMenu =
			// getSupportFragmentManager().findFragmentByTag("pane2").getView();
			roundfb_profilepic = (ImageView) findViewById(R.id.roundfb_profilepic);
			roundfb_profilepic_circle = (ImageView) findViewById(R.id.roundfb_profilepic_circle);
			topPanel_left = (LinearLayout) findViewById(R.id.topPanel_left);
			fbLoginButton = (LoginButton) findViewById(R.id.fbLoginButton);
			topPanel_right_inner_down = (LinearLayout) findViewById(R.id.topPanel_right_inner_down);
			textView_firstname = (TextView) findViewById(R.id.textView_firstname);
			textView_welcome = (TextView) findViewById(R.id.textView_welcome);
			homebtn = (Button) findViewById(R.id.homebtn);

			// NOTE: FO initialize this as False, when sync success this is set
			// to true. This will make sure
			// syncData executes only once.
			if (!FormObject.getInstance().getIsOneTimeExecuted()) {
				FormObject.getInstance().setIsOneTimeExecuted(true);

				retryButton_circle.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						retryButton_circle.startAnimation(rotation_);
						retryButton_circle.setEnabled(false);
						errorTextView.setVisibility(View.GONE);
						Log.e("retry", "onclick executing");
						syncData();
					}
				});

				syncData();
			}

			// rotation = AnimationUtils.loadAnimation(getApplicationContext(),
			// R.anim.rotate_button);
			// rotation.setRepeatCount(Animation.INFINITE);

			if (MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.PLAYING
					|| MyMediaPlayer.getMediaPlayerInstance().isPlaying()) {
				playButton.setChecked(true);
			}
			if (MyMediaPlayer.getIsHDOn()) {
				hdButton.setChecked(true);
			}

			if (MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.BUFFERING) {
				startLoading();
				playButton.setChecked(true);
				playButton.setClickable(true);
				hdButton.setClickable(true);
				nowPlayingInfo1.setText(R.string.bufferring_);
				playbtn_loadingcircle.setVisibility(View.INVISIBLE);
				playerLine1.clearAnimation();
				nowPlayingInfo2.setText("");
			}

			if (MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.PREPARING) {
				startLoading();
				playButton.setChecked(true);
				playButton.setClickable(false);
				hdButton.setClickable(false);
				nowPlayingInfo1.setText(R.string.preparing_);
				playerLine1.clearAnimation();
				nowPlayingWhiteLine.setVisibility(View.INVISIBLE);
				nowPlayingInfo2.setText("");
			}

			if (MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.PLAYING
					|| MyMediaPlayer.getMediaPlayerInstance().isPlaying()) {
				stopLoading();
				playButton.setChecked(true);
			}

			if (MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.PAUSED) {
				stopLoading();
				nowPlayingInfo1.setText(R.string.paused);
				playerLine1.clearAnimation();
				playbtn_loadingcircle.setVisibility(View.INVISIBLE);
				nowPlayingWhiteLine.setVisibility(View.INVISIBLE);
				nowPlayingInfo2.setText("");
			}

			if (MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.FORCE_PAUSED) {
				stopLoading();
				stopPlayerUiReset();
			}

			if (MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.RESETED) {
				stopLoading();
				stopPlayerUiReset();
			}

			if (MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.RELEASED) {
				stopLoading();
				stopPlayerUiReset();
			}
		} catch (Exception e) {
			stopLoading();
			stopPlayerUiReset();

			CustomAlertDialog alertDialog = new CustomAlertDialog(this,
					CusAlrtBtnTypes.OK, CusAlrtIconTypes.DUCK);
			alertDialog.setTitleText(getString(R.string.what_the_duck_));
			//alertDialog.setMessageText(getString(R.string.something_snapped));
			alertDialog.show();
		}
	}

	private void syncData() {
		try {
			new FacebookAsync().execute();
			// new RssDataAsync().execute();
			new SyncDataAsync().execute();
		} catch (Exception e) {
			FormObject.getInstance().setIsSlidingPaneLayoutSlidable(false);
			retryButton_circle.clearAnimation();
			errorTextView.setVisibility(View.VISIBLE);
			retryButton_circle.setEnabled(true);
			FormObject.getInstance().setIsOneTimeExecuted(false);

			CustomAlertDialog alertDialog = new CustomAlertDialog(this,
					CusAlrtBtnTypes.OK, CusAlrtIconTypes.BIRD);
			//alertDialog.setTitleText(getString(R.string.pigeon_s_taken_an_arrow));
			alertDialog
			.setTitleText(getString(R.string.error_sync_issue));
			//alertDialog.setMessageText(getString(R.string.error_sync_issue));
			alertDialog.show();
		}
	}

	public class SyncDataAsync extends
			AsyncTask<String, Void, ResponseDataModel> {

		@Override
		protected ResponseDataModel doInBackground(String... params) {
			ResponseDataModel resp = null;
			try {
				// Sync Date & Time
				resp = getDateTimeData();
				if (resp.isError)
					return resp;

				// if(.getInstance().getUpdateArray()[0])
				// resp = null; // Sync Stream Links
				FormObject.getInstance().setUpdateArrayItemStream(false);

				// if(FormObject.getInstance().getUpdateArray()[1])
				// resp = null; // Sync Weekly Pick
				FormObject.getInstance().setUpdateArrayItemWeeklyPick(false);
				
				if (FormObject.getInstance().getUpdateArray()[2]) { // Sync
																	// Shows
					resp = getOurShowsData();
					if (resp.isError)
						return resp;
				}
				
				if (FormObject.getInstance().getUpdateArray()[3]) { // Sync
																	// Events
					resp = getEventsData();
					if (resp.isError)
						return resp;
				}
			} catch (Exception e) {
				FormObject.getInstance().setDataVersion(1);
				FormObject.getInstance().setIsOneTimeExecuted(false);
				resp.isError = true;
				resp.errorMessage = getString(R.string.error_general);
			}
			return resp;
		}

		@Override
		protected void onPostExecute(ResponseDataModel result) {
			super.onPostExecute(result);

			if (result.isError) {
				FormObject.getInstance().setDataVersion(1);
				MainApplication.foSaveChanges(RadioPlayerActivity.this);

				FormObject.getInstance().setIsSlidingPaneLayoutSlidable(false);
				FormObject.getInstance().setIsOneTimeExecuted(false);
				retryButton_circle.clearAnimation();
				errorTextView.setVisibility(View.VISIBLE);
				retryButton_circle.setEnabled(true);

				if (result.errorMessage == null
						|| result.errorMessage.equals(""))
					result.errorMessage = getString(R.string.error_general);

				CustomAlertDialog alertDialog = new CustomAlertDialog(
						RadioPlayerActivity.this, CusAlrtBtnTypes.OK,
						CusAlrtIconTypes.DUCK);
				//alertDialog.setTitleText(getString(R.string.what_the_duck_));
				alertDialog.setTitleText(result.errorMessage);
				//alertDialog.setMessageText(result.errorMessage);
				alertDialog.show();
			} else {
				FormObject.getInstance().setIsSlidingPaneLayoutSlidable(true);
				FormObject.getInstance().setIsOneTimeExecuted(true);
				retryButton_circle.clearAnimation();
				loading_wrapper.setVisibility(View.GONE);
				btnMenu.setVisibility(View.VISIBLE);
			}Log.e("sync data", "executed");
		}
	}

	public class FacebookAsync extends AsyncTask<String, Void, Boolean> {

		@Override
		protected Boolean doInBackground(String... params) {
			try {
				profilePicWidth = topPanel_left.getWidth();
				profilePicWidth = (int) ((profilePicWidth * 60) / 100);

				if (FormObject.getInstance().getFbLoginStatus()) {
					MainApplication
							.getFacebookProfileData(RadioPlayerActivity.this);

					// If TNL id is null, then do this again and get a TNL id.
					// save it in FO
					if (FormObject.getInstance().getTNLId() == null
							|| FormObject.getInstance().getTNLId().equals(""))
						return sendFacebookDataToTNL();
				}
				return true;
			} catch (Exception e) {
				return false;
			}
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);

			if (FormObject.getInstance().getFbProfilePicture() != null) {
				Bitmap convImg = MainApplication.getByteArrToBitmap(FormObject
						.getInstance().getFbProfilePicture());
				Bitmap img = MainApplication.getRoundedRectBitmap(
						RadioPlayerActivity.this, convImg, false);
				if (img != null)
					roundfb_profilepic.setImageBitmap(img);
				else {
					Bitmap drfault_bm = BitmapFactory.decodeResource(
							getResources(), R.drawable.default_profile_pic);
					Bitmap img1 = MainApplication.getRoundedRectBitmap(
							RadioPlayerActivity.this, drfault_bm, true);
					roundfb_profilepic.setImageBitmap(img1);
				}
			} else {
				// Put default image here
				Bitmap drfault_bm = BitmapFactory.decodeResource(
						getResources(), R.drawable.default_profile_pic);
				Bitmap img1 = MainApplication.getRoundedRectBitmap(
						RadioPlayerActivity.this, drfault_bm, true);
				roundfb_profilepic.setImageBitmap(img1);
			}

			if (FormObject.getInstance().getFbName() != null
					&& FormObject.getInstance().getFbName() != "")
				textView_firstname.setText(FormObject.getInstance().getFbName()
						.split(" ")[0]);
			else
				textView_firstname.setText(R.string.stranger);

			// if(result)
			// sendFacebookDataToTNL();
		}
	}

	private boolean sendFacebookDataToTNL() {
		try {
			HTTPManager httpmanager = new HTTPManager(this);
			ResponseDataModel responseModel = httpmanager
					.sendFacebookUserData();

			if (responseModel.isError && responseModel.responseData == null) {
				return false;
			}

			if (ModelMapper.getLoginDataModel(responseModel) == null) {
				return false;
			} else {
				// Success
				MainApplication.foSaveChanges(this);
				return true;
			}
		} catch (Exception e) {
			return false;
		}
	}

	private ResponseDataModel getOurShowsData() {
		ResponseDataModel responseModel = null;
		try {
			HTTPManager httpmanager = new HTTPManager(this);
			responseModel = httpmanager.getOurShowsData();

			if (responseModel.isError && responseModel.responseData == null) {
				return responseModel;
			}

			List<OurShowsDataModel> showData = ModelMapper
					.getShowsDataModel(responseModel);
			if (showData == null) {
				responseModel.isError = true;
				responseModel.errorMessage = getString(R.string.error_sync_issue);
				return responseModel;
			} else {
				boolean result = true;
				List<OurShowsDataModel> showDataWithImgs = httpmanager
						.downloadOurShowsImages(this, showData);

				for (OurShowsDataModel ourShowsDataModel : showDataWithImgs) {
					if (ourShowsDataModel.imageLink != null
							&& !(ourShowsDataModel.imageLink.equals(""))
							&& ourShowsDataModel.image == null) {
						// result = false;
						// responseModel.isError = true;
						// responseModel.errorMessage =
						// getString(R.string.error_sync_issue);
						break;
					}
				}

				if (result) {
					// Success = true;
					FormObject.getInstance().setShowsData(showDataWithImgs);
					FormObject.getInstance().setUpdateArrayItemShow(false); // No
																			// more
																			// updates
																			// needed
					MainApplication.foSaveChanges(this);
				} else {
					responseModel.isError = true;
					responseModel.errorMessage = getString(R.string.error_sync_issue);
				}
			}
		} catch (Exception e) {
			responseModel.isError = true;
			responseModel.errorMessage = getString(R.string.error_sync_issue);
		}
		return responseModel;
	}

	private ResponseDataModel getEventsData() {
		ResponseDataModel responseModel = null;
		try {
			HTTPManager httpmanager = new HTTPManager(this);
			responseModel = httpmanager.getEventsData();

			if (responseModel.isError && responseModel.responseData == null) {
				return responseModel;
			}

			List<EventsDataModel> eventsData = ModelMapper
					.getEventsDataModel(responseModel);
			if (eventsData == null) {
				responseModel.isError = true;
				responseModel.errorMessage = getString(R.string.error_sync_issue);
				return responseModel;
			} else {
				boolean result = true;
				List<EventsDataModel> eventDataWithImgs = httpmanager
						.downloadEventsImages(this, eventsData);

				for (EventsDataModel eventDataModel : eventDataWithImgs) {
					if (eventDataModel.imageLink != null
							&& !(eventDataModel.imageLink.equals(""))
							&& eventDataModel.image == null) {
						// result = false;
						// responseModel.isError = true;
						// responseModel.errorMessage =
						// getString(R.string.error_sync_issue);
						break;
					}
				}

				if (result) {
					// Success = true;
					FormObject.getInstance().setEventsData(eventDataWithImgs);
					FormObject.getInstance().setUpdateArrayItemEvents(false); // No
																				// more
																				// updates
																				// needed
					MainApplication.foSaveChanges(this);
				} else {
					responseModel.isError = true;
					responseModel.errorMessage = getString(R.string.error_sync_issue);
				}
			}
		} catch (Exception e) {
			responseModel.isError = true;
			responseModel.errorMessage = getString(R.string.error_sync_issue);
		}
		return responseModel;
	}

	private NowPlayingDataModel getNowPlayingData() {
		try {
			HTTPManager httpmanager = new HTTPManager(this);
			ResponseDataModel responseModel = httpmanager.getNowPlayingData();

			if (responseModel.isError && responseModel.responseData == null) {
				return new NowPlayingDataModel();
			}

			NowPlayingDataModel npdm_one = ModelMapper
					.getNowPlayingDataModel(responseModel);
			if (npdm_one.albumArtImageLink != null)
				httpmanager.downloadAlbumArtImage(this,
						npdm_one.albumArtImageLink);
			return npdm_one;
		} catch (Exception e) {
			return new NowPlayingDataModel();
		}
	}

	private ResponseDataModel getDateTimeData() {
		ResponseDataModel responseModel = null;
		try {
			HTTPManager httpmanager = new HTTPManager(this);
			responseModel = httpmanager.getDateTimeData();

			if (responseModel.isError && responseModel.responseData == null) {
				return responseModel;
			}

			boolean result = ModelMapper.getDateTimeDataModel(responseModel);
			if (result) {
				MainApplication.foSaveChanges(this);
			} else {
				responseModel.isError = true;
				responseModel.errorMessage = getString(R.string.error_sync_issue);
				return responseModel;
			}
		} catch (Exception e) {
			responseModel.isError = true;
			responseModel.errorMessage = getString(R.string.error_sync_issue);
		}
		return responseModel;
	}

	public synchronized void onClick_togglePlayClicked(View v) {
		try {
			boolean on = ((ToggleButton) v).isChecked();
			if (on) {
				// Play
				MyMediaPlayer.setMediaPlayerPauseClicked(false);
				handler.removeCallbacks(runnable);

				if (MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.RELEASED
						|| MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.RESETED
						|| MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.FORCE_PAUSED) {

					startLoading();
					Intent intent3 = new Intent(MyMediaPlayer.SVC_NOTIFICATION);
					intent3.putExtra(MyMediaPlayer.VALUE,
							MyMediaPlayerServiceNotifyStatus.GET_AUDIO_FOCUS
									.ordinal());
					sendBroadcast(intent3);

					Intent intent2 = new Intent(MyMediaPlayer.SVC_NOTIFICATION);
					intent2.putExtra(MyMediaPlayer.VALUE,
							MyMediaPlayerServiceNotifyStatus.PREPARE_PLAYER
									.ordinal());
					sendBroadcast(intent2);

					nowPlayingInfo1.setText(R.string.preparing_);
					playerLine1.clearAnimation();
					nowPlayingWhiteLine.setVisibility(View.INVISIBLE);
					nowPlayingInfo2.setText("");
				} else if (MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.PAUSED) {
					Intent intent1 = new Intent(MyMediaPlayer.SVC_NOTIFICATION);
					intent1.putExtra(MyMediaPlayer.VALUE,
							MyMediaPlayerServiceNotifyStatus.PLAY_PLAYER
									.ordinal());
					sendBroadcast(intent1);

					nowPlayingInfo1.setText(R.string.playing_);
					nowPlayingInfo2.setText("");
					playbtn_loadingcircle.setVisibility(View.VISIBLE);
					playerLine1.startAnimation(playerLineAnimation1);
				}

				/*
				 * else if (MyMediaPlayer.getMediaPlayerStatus() ==
				 * MediaPlayerStatus.FORCE_PAUSED) { startLoading();
				 * 
				 * Intent intent3 = new Intent(MyMediaPlayer.SVC_NOTIFICATION);
				 * intent3.putExtra(MyMediaPlayer.VALUE,
				 * MyMediaPlayerServiceNotifyStatus.GET_AUDIO_FOCUS.ordinal());
				 * sendBroadcast(intent3);
				 * //MyMediaPlayer.getMediaPlayerAudioFocus
				 * (getApplicationContext());
				 * 
				 * Intent intent1 = new Intent(MyMediaPlayer.SVC_NOTIFICATION);
				 * intent1.putExtra(MyMediaPlayer.VALUE,
				 * MyMediaPlayerServiceNotifyStatus.PREPARE_PLAYER.ordinal());
				 * sendBroadcast(intent1);
				 * 
				 * //MyMediaPlayer.prepareMediaPlayer();
				 * nowPlayingInfo1.setText("preparing..."); }
				 */

			} else {
				// Pause
				MyMediaPlayer.setMediaPlayerPauseClicked(true);
				stopLoading();
				nowPlayingInfo2.setEllipsize(null);

				nowPlayingInfo1.setText(R.string.paused);
				playbtn_loadingcircle.setVisibility(View.INVISIBLE);
				playerLine1.clearAnimation();
				nowPlayingWhiteLine.setVisibility(View.INVISIBLE);
				nowPlayingInfo2.setText("");

				if (MyMediaPlayer.getMediaPlayerInstance().isPlaying()
						|| MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.PLAYING) {

					Intent intent1 = new Intent(MyMediaPlayer.SVC_NOTIFICATION);
					intent1.putExtra(MyMediaPlayer.VALUE,
							MyMediaPlayerServiceNotifyStatus.PAUSE_PLAYER
									.ordinal());
					sendBroadcast(intent1);

					timerToStopPlayback(timerToStopPlayback);

				} else if (MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.PAUSED) {
					// Don't remove this condition. - Suren
				} else {
					Intent intent1 = new Intent(MyMediaPlayer.SVC_NOTIFICATION);
					intent1.putExtra(MyMediaPlayer.VALUE,
							MyMediaPlayerServiceNotifyStatus.RESET_PLAYER
									.ordinal());
					sendBroadcast(intent1);

					MyMediaPlayer
							.setMediaPlayerStatus(MediaPlayerStatus.FORCE_PAUSED);
					stopPlayerUiReset();
					// nowPlayingInfo1.setText("forcePaused:" +
					// MyMediaPlayer.getMediaPlayerStatus());
				}
			}
		} catch (Exception e) {
			stopLoading();
			// playButton.setChecked(false);
			stopPlayerUiReset();

			CustomAlertDialog alertDialog = new CustomAlertDialog(this,
					CusAlrtBtnTypes.OK, CusAlrtIconTypes.DUCK);
			alertDialog.setTitleText(getString(R.string.what_the_duck_));
			//alertDialog.setMessageText(getString(R.string.something_snapped));
			alertDialog.show();
		}
	}

	public synchronized void onClick_toggleHDClicked(View v) {
		try {
			boolean on = ((ToggleButton) v).isChecked();
			if (on) {
				MyMediaPlayer.setIsHDOn(true);
				if (MyMediaPlayer.getMediaPlayerInstance().isPlaying()
						|| MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.PLAYING) {
					startLoading();
					stopAnimation = true;
					hdButton.startAnimation(animation);

					Intent intent3 = new Intent(MyMediaPlayer.SVC_NOTIFICATION);
					intent3.putExtra(MyMediaPlayer.VALUE,
							MyMediaPlayerServiceNotifyStatus.RESET_N_PREPARE
									.ordinal());
					sendBroadcast(intent3);
					// MyMediaPlayer.resetAndPrepareMediaPlayer();
					nowPlayingInfo1.setText(R.string.preparing_);
					playerLine1.clearAnimation();
					nowPlayingWhiteLine.setVisibility(View.INVISIBLE);
					nowPlayingInfo2.setText("");
				} else {
					Intent intent2 = new Intent(MyMediaPlayer.SVC_NOTIFICATION);
					intent2.putExtra(MyMediaPlayer.VALUE,
							MyMediaPlayerServiceNotifyStatus.RESET_PLAYER
									.ordinal());
					sendBroadcast(intent2);
					// nowPlayingInfo1.setText("reset");
					stopPlayerUiReset();
				}
			} else {
				MyMediaPlayer.setIsHDOn(false);
				if (MyMediaPlayer.getMediaPlayerInstance().isPlaying()
						|| MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.PLAYING) {
					startLoading();
					stopAnimation = true;
					hdButton.startAnimation(animation);

					Intent intent3 = new Intent(MyMediaPlayer.SVC_NOTIFICATION);
					intent3.putExtra(MyMediaPlayer.VALUE,
							MyMediaPlayerServiceNotifyStatus.RESET_N_PREPARE
									.ordinal());
					sendBroadcast(intent3);

					nowPlayingInfo1.setText(R.string.preparing_);
					playerLine1.clearAnimation();
					nowPlayingWhiteLine.setVisibility(View.INVISIBLE);
					nowPlayingInfo2.setText("");

				} else {
					Intent intent2 = new Intent(MyMediaPlayer.SVC_NOTIFICATION);
					intent2.putExtra(MyMediaPlayer.VALUE,
							MyMediaPlayerServiceNotifyStatus.RESET_PLAYER
									.ordinal());
					sendBroadcast(intent2);
					// nowPlayingInfo1.setText("reset");
					stopPlayerUiReset();
				}
			}
		} catch (Exception e) {
			MyMediaPlayer.setIsHDOn(false);
			stopLoading();
			// playButton.setChecked(false);
			hdButton.setChecked(false);
			stopAnimation = false;
			stopPlayerUiReset();

			CustomAlertDialog alertDialog = new CustomAlertDialog(this,
					CusAlrtBtnTypes.OK, CusAlrtIconTypes.DUCK);
			alertDialog.setTitleText(getString(R.string.what_the_duck_));
			//alertDialog.setMessageText(getString(R.string.something_snapped));
			alertDialog.show();

			// hdButton.setClickable(true);
			// Intent intent3 = new Intent(MyMediaPlayer.SVC_NOTIFICATION);
			// intent3.putExtra(MyMediaPlayer.VALUE,
			// MyMediaPlayerServiceNotifyStatus.RELEASE_PLAYER.ordinal()); //
			// value == 6
			// sendBroadcast(intent3);
			// MyMediaPlayer.releaseMediaPlayer();
		}
	}

	private void nowPlayingPolling() {
		new Thread(new Runnable() {
			public void run() {

				while (true) {
					// if(MyMediaPlayer.getMediaPlayerPauseClicked()) break;
					if(!MyMediaPlayer.isPlaying())
					{
						playbtn_loadingcircle.setVisibility(View.INVISIBLE);
						playerLine1.clearAnimation();
					}
					while (MyMediaPlayer.isPlaying()) {
						playbtn_loadingcircle.setVisibility(View.VISIBLE);
						npdm_one = getNowPlayingData();

						while (npdm_one.songName.equals("")) {
							npdm_one = getNowPlayingData();
							updateUi();
						}

						String songName = npdm_one.songName;

						while (npdm_one.songName.equals(songName)) {

							npdm_one = getNowPlayingData();
							updateUi();

							try {
								Thread.sleep(nowPlayingSyncTimer);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}

						// Wait the song to finish and re-check
						try {
							Thread.sleep(npdm_one.songDuration);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}

					// Check play btn is clicked and media playing, time to time
					try {
						Thread.sleep(playBtnClickCheck);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	private void updateUi() {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				/** Jeya */
				boolean isSongNameSet = false,isArtistNameSet = false;
				/** Jeya */
				if (npdm_one == null)
					return;
				if (MyMediaPlayer.getMediaPlayerPauseClicked())
					return;
				if (!MyMediaPlayer.isPlaying())
					return;

				if (FormObject.getInstance().getAlbumArtImage() != null)
					albumart_bg.setImageBitmap(MainApplication
							.getByteArrToBitmap(FormObject.getInstance()
									.getAlbumArtImage()));

				/** Jeya */
				//int songInfoLength = 0;
				String songInfo = "";
				if (npdm_one.songName != null && !npdm_one.songName.equals(""))
				{
					songInfo = npdm_one.songName;
					isSongNameSet = true;				
				}
				else
				{
					nowPlayingInfo2.setText(getString(R.string.please_wait_));
				}
				if (npdm_one.artistName != null && !npdm_one.artistName.equals(""))
				{
					if(isSongNameSet)
					{
						songInfo = songInfo + "|";
					}
					songInfo = songInfo + npdm_one.artistName;
					isArtistNameSet = true;
				}
				if (isSongNameSet || isArtistNameSet) {	
					
					nowPlayingWhiteLine.setVisibility(View.VISIBLE);
					nowPlayingInfo2.setText(songInfo);
					//nowPlayingInfo_two_copy.setText(songInfo);
				/**	int screenWidth = FormObject.getInstance().getScreenWidth();
					int layoutWidth = (int)(screenWidth * 0.4);
					
					Rect bounds = new Rect();
					Paint textPaint = nowPlayingInfo2.getPaint();
					textPaint.getTextBounds(songInfo,0,songInfo.length(),bounds);
					songInfoLength = bounds.width();*/
					
					/**int durationOfLeftOut;// = (int)((4000 * songInfoLength)/85);// right to left
					int durationOfRightIn;// = (int)(2000 * layoutWidth / 128); // left to right
					int startOffsetOfRightIn;// = durationOfLeftOut + 5000 - durationOfRightIn; // 7000
					
					durationOfLeftOut = 4000;
					durationOfRightIn = 4000;
					
					left_out.setDuration(durationOfLeftOut);
					right_in.setDuration(durationOfRightIn);*/
					
					//nowPlayingInfo_two_copy.startAnimation(left_out);
					nowPlayingInfo2.setEllipsize(TextUtils.TruncateAt.MARQUEE);
				}
				/** Jeya */
			}
		});
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// preventing default implementation previous to
			// android.os.Build.VERSION_CODES.ECLAIR
			Intent i = new Intent();
			i.setAction(Intent.ACTION_MAIN);
			i.addCategory(Intent.CATEGORY_HOME);
			this.startActivity(i);

			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		Intent intent1 = new Intent(MyMediaPlayer.SVC_NOTIFICATION);
		intent1.putExtra(MyMediaPlayer.VALUE,
				MyMediaPlayerServiceNotifyStatus.RELEASE_PLAYER.ordinal());
		sendBroadcast(intent1);
	}

	private void startLoading() {
		try {
			if (MyMediaPlayer.getMediaPlayerPauseClicked())
				return;

			playbtn_loadingcircle.startAnimation(rotation);

			if (MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.BUFFERING) {
				playButton.setClickable(true);
				hdButton.setClickable(true);
			} else {
				playButton.setClickable(false);
				hdButton.setClickable(false);
			}
		} catch (Exception e) {
			CustomAlertDialog alertDialog = new CustomAlertDialog(this,
					CusAlrtBtnTypes.OK, CusAlrtIconTypes.DUCK);
			alertDialog.setTitleText(getString(R.string.what_the_duck_));
			//alertDialog.setMessageText(getString(R.string.something_snapped));
			alertDialog.show();
		}
	}

	private void stopLoading() {
		try {
			playbtn_loadingcircle.clearAnimation();

			playButton.setClickable(true);
			hdButton.setClickable(true);
			stopAnimation = false;

			playButton.setChecked(false); // 2014-10-03 added for debugging
											// purposes
		} catch (Exception e) {
			CustomAlertDialog alertDialog = new CustomAlertDialog(this,
					CusAlrtBtnTypes.OK, CusAlrtIconTypes.DUCK);
			alertDialog.setTitleText(getString(R.string.what_the_duck_));
			//alertDialog.setMessageText(getString(R.string.something_snapped));
			alertDialog.show();
		}
	}

	private synchronized void timerToStopPlayback(int time) {
		try {
			// Handler handler = new Handler();
			handler.removeCallbacks(runnable);
			handler.postDelayed(runnable = new Runnable() {
				@Override
				public void run() {
					if (!MyMediaPlayer.getMediaPlayerInstance().isPlaying()
							&& MyMediaPlayer.getMediaPlayerStatus() != MediaPlayerStatus.PLAYING) {

						Intent intent2 = new Intent(
								MyMediaPlayer.SVC_NOTIFICATION);
						intent2.putExtra(MyMediaPlayer.VALUE,
								MyMediaPlayerServiceNotifyStatus.RESET_PLAYER
										.ordinal()); // value == 1
						sendBroadcast(intent2);

						stopPlayerUiReset();
					}
				}
			}, time);
		} catch (Exception e) {
		}
	}

	private void stopPlayerUiReset() {
		playButton.setChecked(false);
		String welcomeText = "Welcome" + " " + username;
		nowPlayingInfo1.setText(welcomeText);
		playbtn_loadingcircle.setVisibility(View.INVISIBLE);
		playerLine1.clearAnimation();
		nowPlayingInfo2.setText("");
		nowPlayingWhiteLine.setVisibility(View.INVISIBLE);
		FormObject.getInstance().setAlbumArtImage(null);
		albumart_bg.setImageDrawable(null);
	}

	private void startNotificationOnStatusBar() {
		try {
			Intent intent3 = new Intent(MyMediaPlayer.SVC_NOTIFICATION);
			intent3.putExtra(MyMediaPlayer.VALUE,
					MyMediaPlayerServiceNotifyStatus.START_NOTIFICATION
							.ordinal()); // value == 7
			sendBroadcast(intent3);
		} catch (Exception e) {
		}
	}

	private void stopNotificationOnStatusBar() {
		try {
			Intent intent2 = new Intent(MyMediaPlayer.SVC_NOTIFICATION);
			intent2.putExtra(MyMediaPlayer.VALUE,
					MyMediaPlayerServiceNotifyStatus.STOP_NOTIFICATION
							.ordinal()); // value == 8
			sendBroadcast(intent2);
		} catch (Exception e) {
		}
	}

	private synchronized void myMediaPlayerServiceCallbacks() {
		try {
			br_commonReceiver = new BroadcastReceiver() {
				@Override
				public void onReceive(Context context, Intent intent) {
					int value = 0;
					if (intent == null)
						value = 0;
					else
						value = intent.getIntExtra(MyMediaPlayer.VALUE, 0); // 0
																			// value
																			// has
																			// an
																			// issue
																			// TODO:
																			// check
																			// this

					MyMediaPlayerActivityNotifyStatus whichView = MyMediaPlayerActivityNotifyStatus
							.values()[value];

					switch (whichView) {
					case CONNECTIVITY:
						stopLoading();
						// playButton.setChecked(true); // 2014-10-03 removed
						// due to conn lost and still play clicked issue
						stopPlayerUiReset();
						break;

					case HEADSET_UNMOUNTED:
						if (MyMediaPlayer.getMediaPlayerInstance().isPlaying()) {
							playButton.setChecked(false);
							timerToStopPlayback(timerToStopPlayback);
						}
						break;

					case AUDIO_FOCUS_LOST:
						if (MyMediaPlayer.getMediaPlayerInstance().isPlaying()) {
							stopLoading();
							stopPlayerUiReset();
						}
						break;

					// Lost focus for a short time, but we have to stop
					// playback. We don't release the media player because
					// playback
					// is likely to resume
					case AUDIOFOCUS_LOSS_TRANSIENT: // Pause the player
						playButton.setChecked(false);
						timerToStopPlayback(timerToStopPlayback);
						break;

					case PREPARE_PLAYER: // Pause the player
						if (MyMediaPlayer.getMediaPlayerPauseClicked())
							return;
						nowPlayingInfo1.setText(R.string.preparing_);
						playerLine1.clearAnimation();
						nowPlayingWhiteLine.setVisibility(View.INVISIBLE);
						nowPlayingInfo2.setText("");
						startLoading();
						playButton.setChecked(true);
						break;

					case PLAY_PLAYER: // Pause the player
						nowPlayingInfo1.setText(R.string.playing_);
						playbtn_loadingcircle.setVisibility(View.VISIBLE);
						playerLine1.startAnimation(playerLineAnimation1);
						nowPlayingInfo2.setText("");
						playButton.setChecked(true);
						break;

					case ON_PREPARED:
						stopLoading();
						if (MyMediaPlayer.getMediaPlayerStatus() != MediaPlayerStatus.FORCE_PAUSED) {
							nowPlayingInfo1.setText(R.string.playing_);
							playbtn_loadingcircle.setVisibility(View.VISIBLE);
							nowPlayingInfo2.setText("");
							playerLine1.startAnimation(playerLineAnimation1);
							playButton.setChecked(true);
						}
						break;

					case ON_COMPLETION:
						boolean isError = intent.getBooleanExtra("isError",
								false);
						int isError_ErrorCode = intent.getIntExtra(
								"isError_ErrorCode", -1);

						if (isError) {
							// nowPlayingInfo1.setText("on complete - error");
							stopLoading();
							stopPlayerUiReset();

							CustomAlertDialog alertDialog = new CustomAlertDialog(
									RadioPlayerActivity.this,
									CusAlrtBtnTypes.OK, CusAlrtIconTypes.TAPE);
							/*alertDialog.setTitleText(context
									.getString(R.string.tape_tangled_));*/

							switch (isError_ErrorCode) {
							case -1004:
								/*alertDialog
										.setMessageText(context
												.getString(R.string.media_server_error_));*/
								alertDialog.setTitleText(context
										.getString(R.string.media_server_error_));
								alertDialog.show();
								break;
							case -1007:
								/*alertDialog
										.setMessageText(context
												.getString(R.string.malformed_media_server_));*/
								alertDialog.setTitleText(context
										.getString(R.string.malformed_media_server_));
								alertDialog.show();
								break;
							case 200:
								/*alertDialog
										.setMessageText(context
												.getString(R.string.media_server_playback_error_));*/
								alertDialog.setTitleText(context
										.getString(R.string.media_server_playback_error_));
								alertDialog.show();
								break;
							case 100:
								/*alertDialog
										.setMessageText(context
												.getString(R.string.r_i_p_media_server_));*/
								alertDialog.setTitleText(context
										.getString(R.string.r_i_p_media_server_));
								alertDialog.show();
								break;
							case -110:
								/*alertDialog
										.setMessageText(context
												.getString(R.string.media_server_time_out_));*/
								alertDialog.setTitleText(context
										.getString(R.string.media_server_time_out_));
								alertDialog.show();
								break;
							case 1:
								/*alertDialog
										.setMessageText(context
												.getString(R.string.unknown_media_server_error_));*/
								alertDialog.setTitleText(context
										.getString(R.string.unknown_media_server_error_));
								alertDialog.show();
								break;
							case -1010:
								/*alertDialog
										.setMessageText(context
												.getString(R.string.media_server_not_supported_));*/
								alertDialog.setTitleText(context
										.getString(R.string.media_server_not_supported_));
								alertDialog.show();
								break;
							}
							playButton.setChecked(false);
						} else {
							startLoading();
						}
						break;

					case ON_BUFFERING_UPDATE:
						int percent = intent.getIntExtra("percent", -1);
						if (percent == 100) {
							startLoading();
							playButton.setClickable(true);
							hdButton.setClickable(true);
						}
						break;

					case ON_INFO:
						int what = intent.getIntExtra("what", -1);
						if (what == 701 || what == 703) {
							startLoading();
							nowPlayingInfo1.setText(R.string.bufferring_);
							playbtn_loadingcircle.setVisibility(View.INVISIBLE);
							nowPlayingInfo2.setText("");
							playerLine1.clearAnimation();
							playButton.setClickable(true);
							hdButton.setClickable(true);
							MyMediaPlayer
									.setMediaPlayerStatus(MediaPlayerStatus.BUFFERING);
						} else if (what == 702) {
							nowPlayingInfo1.setText(R.string.playing_);
							nowPlayingInfo2.setText("");
							playbtn_loadingcircle.setVisibility(View.VISIBLE);
							playerLine1.startAnimation(playerLineAnimation1);
							stopLoading();
						} else {
							stopLoading();
						}
						break;

					case ON_ERROR:
						MyMediaPlayer
								.setMediaPlayerStatus(MediaPlayerStatus.RELEASED);
						stopPlayerUiReset();
						nowPlayingInfo1.setText(R.string.media_player_error_);
						nowPlayingInfo2.setText("");
						playbtn_loadingcircle.setVisibility(View.INVISIBLE);
						stopLoading();

						CustomAlertDialog alertDialog = new CustomAlertDialog(
								RadioPlayerActivity.this, CusAlrtBtnTypes.OK,
								CusAlrtIconTypes.TAPE);
						alertDialog.setTitleText(context
								.getString(R.string.media_player_error_));
						/*alertDialog.setTitleText(context
								.getString(R.string.tape_tangled_));
						alertDialog.setMessageText(context
								.getString(R.string.media_player_error_));*/
						alertDialog.show();
						break;

					default:
						Intent intent3 = new Intent(
								MyMediaPlayer.SVC_NOTIFICATION);
						intent3.putExtra(MyMediaPlayer.VALUE,
								MyMediaPlayerServiceNotifyStatus.RESET_PLAYER
										.ordinal());
						sendBroadcast(intent3);
						stopLoading();
						stopPlayerUiReset();
						break;
					}
				}
			};
			// SVC sending ACTIVITY Notifications
			registerReceiver(br_commonReceiver, new IntentFilter(
					MyMediaPlayer.ACT_NOTIFICATION));
		} catch (Exception e) {
			stopLoading();
			stopPlayerUiReset();

			CustomAlertDialog alertDialog = new CustomAlertDialog(this,
					CusAlrtBtnTypes.OK, CusAlrtIconTypes.DUCK);
			alertDialog.setTitleText(getString(R.string.what_the_duck_));
			//alertDialog.setMessageText(getString(R.string.something_snapped));
			alertDialog.show();
		}
	}
}